package com.temple.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.comon.core.domain.result.R;
import com.comon.core.enums.ResultCode;

import com.temple.config.UserClientService;
import com.temple.model.card.VO.SelfNumberInfo;
import com.temple.model.circle.CircleInfo;
import com.temple.model.circle.DTO.CircleDTO;
import com.temple.model.circle.DTO.CircleInfoDTO;
import com.temple.model.circle.DTO.MyCircleDTO;
import com.temple.model.circle.DTO.PopularTemple;
import com.temple.model.favor.UserFavor;
import com.temple.service.CircleService;
import com.temple.mapper.circleMapper;
import com.temple.mapper.favorMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.*;

/**
 * Created with Intellij IDEA.
 * Description;
 * User:TQ02
 * Data:2024-09-07
 * Time:16:51
 * Text：
 */
@Service
public class CircleServiceImpl extends ServiceImpl<circleMapper,CircleInfo> implements CircleService {
    @Autowired
    private  circleMapper circleMapper;
    @Autowired
    private favorMapper favorMapper;
    @Autowired
    private UserClientService userClientService;

    private final String Id = "http://120.46.91.1:9000/test/";

    public R<?> createTemple(CircleDTO circleDTO, MultipartFile file, Long Uid) throws IOException {
        boolean isName = circleMapper.selectOne(new LambdaQueryWrapper<CircleInfo>().eq(CircleInfo::getCircleName, circleDTO.getCircle())) != null;
        if (isName) {
            return R.fail(4001, "殿堂已存在");
        }

        CircleInfo circleInfo = new CircleInfo();
        circleInfo.setCircleName(circleDTO.getCircle());
        circleInfo.setCircleNumber(circleDTO.getCircleNumber());
        circleInfo.setContent(circleDTO.getContent());
        circleInfo.setUId(Uid);

        // 获取文件名
        String uuid = String.valueOf(UUID.randomUUID());
        String newFilename = file.getOriginalFilename();
        if (newFilename != null) {
            circleInfo.setPhoto(Id+newFilename);  // Assuming 'Id' was meant to be part of filename logic
        }

        userClientService.setFile(file);

        // 将数据插入数据库中
        int saved = circleMapper.insert(circleInfo);
        if (saved != 1) {
            return R.fail(4002, "数据保存失败");
        }

        return R.ok();
    }
    public R<?> EditTemple(CircleInfo circleInfo, MultipartFile file, Long Uid)  {
        // 获取文件名
        String uuid = String.valueOf(UUID.randomUUID());
        String newFilename = file.getOriginalFilename();
        if (newFilename != null) {
            circleInfo.setPhoto(newFilename);  // Assuming 'Id' was meant to be part of filename logic
        }

        userClientService.setFile(file);

        // 将数据插入数据库中
        int saved = circleMapper.updateById(circleInfo);
        if (saved != 1) {
            return R.fail(4002, "数据保存失败");
        }
        return R.ok();
    }

    /*
     * @description: 获取关注殿堂的人员信息
     * @param id  殿堂序号
     * @return: R<List<MyCircleDTO>>
    **/
    @Override
    public R<List<SelfNumberInfo>> getTempleNumberInfo(int id) {
        List<UserFavor> list = favorMapper.selectList(new LambdaQueryWrapper<UserFavor>().eq(UserFavor::getCirId,id));
        List<SelfNumberInfo> list1 = new ArrayList<>();
        for(UserFavor userFavor:list){
            SelfNumberInfo selfNumberInfo = new SelfNumberInfo();
            String photo = userClientService.getPhotoById(userFavor.getUserId());
            selfNumberInfo.setName(userFavor.getUserName());
            selfNumberInfo.setPhoto(photo);
            selfNumberInfo.setUserId(userFavor.getUserId().toString());
            selfNumberInfo.setPosition(userFavor.getPosition());
            list1.add(selfNumberInfo);
        }
        return R.ok(list1);
    }

    @Override
    public R<List<MyCircleDTO>> getMyTemple(Long Uid) {
        List<CircleInfo> circles = circleMapper.selectList(new LambdaQueryWrapper<CircleInfo>().eq(CircleInfo::getUId,Uid));
        List<MyCircleDTO> MyCircles = new LinkedList<>();
        for(CircleInfo circleInfo:circles){
            MyCircleDTO myCircleDTO = new MyCircleDTO();
            myCircleDTO.setName(circleInfo.getCircleName());
            myCircleDTO.setPhoto(circleInfo.getPhoto());
            myCircleDTO.setCreateTime(circleInfo.getCreateTime());
            myCircleDTO.setState("殿主");
            MyCircles.add(myCircleDTO);
        }
        return R.ok(MyCircles);
    }

    @Override
    public R<List<PopularTemple>> getTemple() {
// 创建分页对象，指定当前页和每页条数
        Page<CircleInfo> page = new Page<>(1, 20, false); // false 表示不统计总记录数

// 执行分页查询，按时间戳降序排列以获取最新的 20 条记录
        IPage<CircleInfo> result = circleMapper.selectPage(page,
                new LambdaQueryWrapper<CircleInfo>()
                        .orderByDesc(CircleInfo::getCreateTime)); // 根据时间戳降序排列
// 获取分页结果中的记录列表
        List<CircleInfo> circles = result.getRecords();
// 如果需要按时间戳从旧到新排序，可以再次排序
        circles.sort(Comparator.comparing(CircleInfo::getCreateTime));
        List<PopularTemple> popularTemples = new LinkedList<>();
        for(CircleInfo circleInfo:circles){
            PopularTemple popularTemple = new PopularTemple();
            popularTemple.setCircleName(circleInfo.getCircleName());
            popularTemple.setPhoto(circleInfo.getPhoto());
            popularTemple.setCirId(circleInfo.getCirId());
            Long num = favorMapper.selectCount(new LambdaQueryWrapper<UserFavor>().eq(UserFavor::getCirId,circleInfo.getCirId()));
            popularTemple.setPeopleNum(num);
            /*
                帖子数暂定为0
            **/
            popularTemple.setPlNum(1);
            popularTemples.add(popularTemple);
        }
        return R.ok(popularTemples);
    }

    @Override
    public R<?> getTempleInfo(Long id, Long u_id) {
        CircleInfoDTO circleInfoDTO = new CircleInfoDTO();

        CircleInfo circleInfo = circleMapper.selectOne(new LambdaQueryWrapper<CircleInfo>().eq(CircleInfo::getCirId, id));
        if (circleInfo == null) {
            return R.fail(ResultCode.FAILED_NOT_EXISTS);
        }

        circleInfoDTO.setCircleName(circleInfo.getCircleName());
        circleInfoDTO.setContent(circleInfo.getContent());
        circleInfoDTO.setTzNumber(0);
        circleInfoDTO.setPhoto(circleInfo.getPhoto());
        Long num = favorMapper.selectCount(new LambdaQueryWrapper<UserFavor>().eq(UserFavor::getCirId,id));
        circleInfoDTO.setGzPeople(num);

        UserFavor isConcerned = favorMapper.selectOne(new LambdaQueryWrapper<UserFavor>().eq(UserFavor::getUserId, u_id).eq(UserFavor::getCirId,id)) ;
        //为空时，则未关注，标为-1；若是创建者，则标为1；若是关注者标为2
        if(isConcerned == null){
            circleInfoDTO.setConcern(-1);
        }else if(isConcerned.getPosition()==1){
            circleInfoDTO.setConcern(1);
        }else{
            circleInfoDTO.setConcern(2);
        }

        String name = userClientService.getUserById(u_id);
        circleInfoDTO.setCreateName(name);

        return R.ok(circleInfoDTO);
    }

    @Override
    public R<?> setAttention(int id, Long uId) {
        UserFavor userFavor = new UserFavor();
        userFavor.setUserId(uId);
        userFavor.setCirId(id);
        userFavor.setPosition(2);
        String name = userClientService.getUserById(uId);
        userFavor.setUserName(name);
        favorMapper.insert(userFavor);
        return R.ok("关注成功");
    }

    @Override
    public R<?> unAttention(int id, Long uId) {
        int i = favorMapper.delete(new LambdaQueryWrapper<UserFavor>().eq(UserFavor::getUserId,uId).eq(UserFavor::getCirId,id));
        return i == 0?R.fail(ResultCode.FAILED_NOT_EXISTS):R.ok(ResultCode.SUCCESS);
    }


    /**
     * @description:获取对应的殿堂信息
     * @param id
     * @return: R<?>
    **/
    @Override
    public R<?> getEditTemple(Long id) {
        CircleInfo circleInfo = circleMapper.selectOne(new LambdaQueryWrapper<CircleInfo>().eq(CircleInfo::getCirId,id));
        return R.ok(circleInfo);
    }


}
